package org.hackystat.projectbrowser.page.settrigger;

import java.util.List;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.hackystat.ambientdevice.server.jaxb.Project;
import org.hackystat.ambientdevice.server.jaxb.Trigger;
import org.hackystat.ambientdevice.server.jaxb.TriggerActionPair;
import org.hackystat.projectbrowser.ProjectBrowserSession;

/**
 * The class form that creates a new trigger.
 * 
 * @author Edward Kim
 * 
 */
public class NewTriggerNameForm extends StatelessForm {

  /** Supports serialization. */
  private static final long serialVersionUID = 1L;

  private String tempTAP;
  private String projectName;
  private String tapName;
  private PageParameters responseParam = new PageParameters();

  /**
   * The form that creates a new trigger.
   * 
   * @param id A String passed on to the super (not really needed).
   * @param projectName The current project name.
   * @param tapName the current trigger/action pair name.
   */
  public NewTriggerNameForm(String id, String projectName, String tapName) {
    super(id);

    this.projectName = projectName;
    this.tapName = tapName;
    responseParam.add("projectName", this.projectName);
    responseParam.add("tapName", this.tapName);

    setModel(new CompoundPropertyModel(this));
    add(new TextField("tempTAP"));
  }

  /**
   * When the form is submiting, check for errors and try to create a new project.
   */
  @Override
  public void onSubmit() {
   
    Project tempProject = ProjectBrowserSession.get().getProjectTypeXMLByNameId(projectName);
    for (TriggerActionPair pair : tempProject.getTriggerActionPairs().getTriggerActionPair()) {
      if (pair.getId().equals(this.tapName)) {
        if (pair.getTriggers() == null) {
          TriggerActionPair.Triggers TAP = new TriggerActionPair.Triggers();
          Trigger newTrigger = new Trigger();
          newTrigger.setId(this.tempTAP);
          TAP.getTrigger().add(newTrigger);
          pair.setTriggers(TAP);
        }
        else {
          List<Trigger> triggers = pair.getTriggers().getTrigger();
          Trigger newTrigger = new Trigger();
          newTrigger.setId(this.tempTAP);
          triggers.add(newTrigger);
        }
      }
    }
    // set response page to go back to chooseTAP
    setResponsePage(ChooseTrigger.class, responseParam);
  }

  /**
   * The setter for the temp trigger/action pair.
   * 
   * @param tempTAP The temp TAP.
   */
  public void setTempTAP(String tempTAP) {
    this.tempTAP = tempTAP;
  }

  /**
   * The getter for the temp TAP.
   * 
   * @return The temp TAP.
   */
  public String getTempTAP() {
    return tempTAP;
  }

}
